package org.example.erat.strategy;

import org.example.erat.dto.StudentStatisticsDTO;
import org.example.erat.entity.ClassEntity;
import org.example.erat.entity.Course;
import org.example.erat.entity.Experiment;
import org.example.erat.entity.Student;
import org.example.erat.log.core.LoggerSingleton;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 学生维度统计策略
 * 按学生维度统计提交情况
 */
@Component
public class StudentStatisticsStrategy implements StatisticsStrategy {

    @Override
    public Map<String, Object> execute(ClassEntity classEntity, Course course,
                                     List<Student> students, List<Experiment> experiments,
                                     Map<String, Object> reportData) {
        LoggerSingleton.getInstance().info("执行学生维度统计策略");

        Map<String, Object> result = new HashMap<>();
        List<StudentStatisticsDTO> studentStatistics = new ArrayList<>();

        // 获取已提交的学生ID集合
        @SuppressWarnings("unchecked")
        Map<String, Set<String>> submittedStudentIds = (Map<String, Set<String>>) reportData.getOrDefault("submittedStudentIds", new HashMap<>());

        // 计算每个学生的统计数据
        for (Student student : students) {
            StudentStatisticsDTO stats = new StudentStatisticsDTO();
            stats.setStudentId(student.getStudentId());
            stats.setName(student.getName());
            stats.setTotalCount(experiments.size());

            // 计算缺交实验数量和列表
            List<Map<String, Object>> missingExperiments = new ArrayList<>();
            int missingCount = 0;

            for (Experiment experiment : experiments) {
                Set<String> submittedIds = submittedStudentIds.getOrDefault(experiment.getName(), new HashSet<>());
                if (!submittedIds.contains(student.getStudentId())) {
                    missingCount++;
                    Map<String, Object> missingExperiment = new HashMap<>();
                    missingExperiment.put("id", experiment.getId());
                    missingExperiment.put("name", experiment.getName());
                    missingExperiments.add(missingExperiment);
                }
            }

            stats.setMissingCount(missingCount);
            stats.setMissingExperiments(missingExperiments);

            // 计算提交率
            if (stats.getTotalCount() > 0) {
                stats.setSubmissionRate(1.0 - (double) stats.getMissingCount() / stats.getTotalCount());
            } else {
                stats.setSubmissionRate(0.0);
            }

            studentStatistics.add(stats);
        }

        result.put("studentStatistics", studentStatistics);

        LoggerSingleton.getInstance().info("学生维度统计完成，共 {} 名学生", studentStatistics.size());
        return result;
    }

    @Override
    public String getName() {
        return "student";
    }
}
